Skip to content

perf(ios): streaming, Live Activity and network lifecycle - #331

Merged
sambitcreate merged 11 commits into
mainfrom
perf/ios-streaming
Oct 4, 2026
Merged

sambitcreate merged 11 commits into
mainfrom
perf/ios-streaming

Conversation

@sambitcreate

@sambitcreate sambitcreate commented Oct 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Live Activity (EXT-9): updates are coalesced to about once a second.
  • Markdown (EXT-10): parsed chunks are reused while streaming.
  • Refetch (EXT-11, partial): happens only when the app returns from the background.
  • Streaming (EXT-12, EXT-17): a single owner for the progress snapshot, plus jittered backoff.
  • Keychain (EXT-13): the active client cache is checked before reading the Keychain.
  • Sessions (EXT-14, EXT-16): interactive calls are bounded, the stream session is split out, and sessions are released.
  • Motion (EXT-18): the thinking orb is capped at 30 fps, and decorative motion is held in Low Power Mode.
  • SSE (EXT-19): lines are decoded with per-line cancellation and validation.

Test plan

  • iOS unit tests: 361 pass on the simulator.

Part of the October optimization pass. Finding IDs refer to docs/performance/optimization-audit-2026-10-03.md (#320). The branch's .memory/ note has per-finding rationale.

🤖 Generated with Claude Code

Flake recorded

🤖 Generated with Claude Code

sambitcreate and others added 9 commits October 3, 2026 06:53
…XT-9)

Streamed tokens, reasoning, and tool churn now write ActivityKit at most
once per second with the newest state. Status changes, approval, stale,
and end bypass the window and supersede any pending write, so a phase
change is never delayed or overwritten by an older coalesced update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…2, EXT-17)

Chat open fetched the progress snapshot in load() and again in the
observer before its live channel delivered the same snapshot. load() now
hands its snapshot to the observer, and a reload while the observer runs
leaves progress to it. Reconnects use capped exponential backoff with
equal jitter instead of a fixed one-second retry, resetting after any
delivered event; stream reconciliation shares the jittered policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Settled blank-line-delimited blocks are parsed once and cached in a bounded
LRU; each streamed update reparses only the open tail. The live response
view evaluates its transcript projections once per render.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… (EXT-19)

Extracts the SSE line splitter so the stream loop does one compare and one
append per byte, checking cancellation and validating UTF-8 once per line.
Framing is unchanged: LF/CRLF endings, blank delimiters, EOF discard, and
the frame-size limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sions (EXT-14, EXT-16)

Request/response calls use a session with a 5 minute resource budget; SSE
streams keep the 1 hour budget with the 30 s idle timeout as liveness (two
missed 15 s heartbeats). Clients invalidate the sessions they create when
released, so replaced clients no longer leak sessions and delegates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…(EXT-13)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…in Low Power Mode (EXT-18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Transient inactive bounces (Control Center, app switcher, system prompts)
no longer rerun the full reconnect or chat reload, or stop progress
streams. A newer chat load epoch cancels an older in-flight load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

Two regressions should be fixed before merging: foreground progress observation can fail to resume, and Markdown chunking can turn valid reference links into plain text.

Reviewed changes: Reviewed all 17 changed files covering iOS streaming performance, lifecycle ownership, rendering, and focused behavioral tests.

  • Live Activities: Added latest-value throttling with urgent status updates and cancellation on activity completion.
  • Markdown rendering: Added bounded parsed-chunk reuse and reduced repeated live-response projections.
  • Progress and lifecycle: Reused initial progress snapshots, added jittered reconnect backoff, and restricted scene refetches to background returns.
  • Networking: Moved client-cache lookup ahead of Keychain reads, split interactive and SSE sessions, added owned-session invalidation, and extracted per-line SSE decoding.
  • Motion and coverage: Capped orb animation, paused decorative motion in Low Power Mode, and added source registrations and behavioral tests.

Validation included executing the actual Markdown splitter against a quoted reference definition and checking the pinned MarkdownUI implementation. iOS XCTest could not be run on this Linux runner because xcodebuild is unavailable.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

}
switch sceneRefreshGate.transition(to: phase) {
case .refresh:
chatLoadEpoch &+= 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep foreground progress resumption independent of a dropped load

If the app backgrounds while load() is suspended, this replacement task can enter before the cancelled load releases isLoading, so the foreground load immediately returns. Backgrounding already stopped progress observation, and the old load cannot restart it with its invalidated generation, leaving progress stale with no reconnect owner if the coordinator refresh also fails.

Technical details
# Lost foreground progress restart

## Affected sites
- `ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:4189-4198` - changing the epoch cancels/restarts loading; the separate observer task is keyed only by serverTime.
- `ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1538,1613-1623` - a replacement load is dropped while isLoading is true; the older load fails its observation generation/cancellation check.
- `ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:1802-1808,4254-4260` - background stops the observer, but foreground refresh does not explicitly resume it.

## Required outcome
- Ensure background return eventually reloads and resumes progress even when an older load is still unwinding, without depending on a successful serverTime update.
- Extend behavioral lifecycle coverage with a deterministically suspended load: background, foreground while the old load remains suspended, release it, then verify progress observation resumes and retries after network recovery.

## Contract evidence
- Swift cancellation is cooperative, not a join: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0304-structured-concurrency.md#cancellation
- A successful coordinator refresh can mask this, but the error path at `AidenRemoteCoordinator.swift:937-969` leaves serverTime unchanged.

let utf8 = text.utf8
while lineStart < utf8.endIndex {
let lineEnd = utf8[lineStart...].firstIndex(of: 0x0A) ?? utf8.endIndex
if looksLikeDefinition(utf8[lineStart..<lineEnd]) { return false }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Detect reference definitions inside containers before splitting

This scan misses quoted definitions such as > [foo]: /url, although CommonMark applies them to the entire document. For [foo]\n\n> [foo]: /url\n, the splitter settles the first paragraph separately, so the new renderer displays literal [foo] instead of the link that a full MarkdownContent parse produces.

Technical details
# Container definitions lose document-wide link resolution

## Affected sites
- `ios/AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift:55-84` - definition detection does not account for container prefixes.
- `ios/AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift:192-201` - chunks are parsed separately and their existing blocks are concatenated.
- `ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift:6064` - this affects settled transcript messages as well as streaming output.

## Required outcome
- Preserve full-document reference resolution for definitions in block quotes/list containers; fall back to a full parse when independent chunk parsing cannot preserve semantics.
- Add this fixture to the existing every-prefix equivalence test, including its terminating newline:

```markdown
[foo]

> [foo]: /url
```

## Contract evidence
- CommonMark explicitly states that definitions inside containers affect the whole document: https://spec.commonmark.org/0.31.2/#example-218
- Pinned MarkdownUI composition only flattens parsed block arrays; it does not re-resolve links: https://github.com/gonzalezreal/swift-markdown-ui/blob/5f613358148239d0292c0cef674a3c2314737f9e/Sources/MarkdownUI/DSL/Blocks/MarkdownContent.swift
- Executing the actual splitter on this head produced settled `[foo]\n\n` and tail `> [foo]: /url\n`.

@very-hermes-bot

Copy link
Copy Markdown
Collaborator

Hermes Review Bot

Confidence: 5

Engine: agy/gemini-3.8-flash-high
Review mode: full
Head: a28a1f7c3a7921a956e2424a065a05bbf95c28b3
Generated: 2026-10-04T06:01:07+00:00
Reviews: 1

Summary

Coalesces high-frequency iOS streaming updates across Live Activities, Markdown rendering, and network lifecycles to optimize power and CPU usage. Live Activity updates are throttled to at most one write per second using AidenLatestValueThrottle with urgent bypass for phase changes, while AidenMarkdownContentCache splits documents at safe CommonMark block boundaries to avoid quadratic re-parsing during token streaming. Network resources are tightened by separating interactive requests (5-minute resource timeout) from SSE streams (30-second idle timeout keyed to 15-second heartbeats), invalidating owned URLSession instances upon client deallocation, caching the active client in AidenRemoteCoordinator before Keychain access, and deduplicating progress snapshot loading with jittered exponential backoff. Maintainers should double-check that third-party reverse proxies or firewalls deployed in front of the Aiden server reliably pass the 15-second SSE heartbeat comments to prevent the 30-second idle timeout from prematurely disconnecting active streams.

Confidence Score: 5/5

5/5 — All changed files, lifecycle transitions, concurrency/actor isolation contracts, CommonMark block boundary rules, and Xcode project build phases were traced end-to-end and verified against behavioral test suites.

📁 Important Files Changed
  • ios/AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift: Coalesces high-frequency values to at most once per interval while immediately delivering urgent updates and cancelling stale flushes.
  • ios/AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift: Integrates the throttle for token, reasoning, and tool updates while keeping status, stale, and termination updates immediate.
  • ios/AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift: Splits streamed Markdown into settled blocks at safe blank-line boundaries, reusing parsed chunks via an LRU cache so only the open tail is reparsed.
  • ios/AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift: Filters out transient .inactive scene phase bounces (Control Center, Notification Center) and triggers reconnection only after returning from .background.
  • ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift: Deduplicates progress snapshot loading between load() and progress observation, adopts jittered reconciliation backoff, single-evaluates live response projections, and binds chat refresh to the scene gate.
  • ios/AidenOnTheGo/Networking/AidenRemoteClient.swift: Separates interactive calls from SSE streams with custom session policies, invalidates owned URLSession instances in deinit, and delegates SSE line reading to AidenSSELineDecoder.
  • ios/AidenOnTheGo/Networking/AidenSSEParser.swift: Adds AidenSSELineDecoder to process byte streams line-by-line with UTF-8 validation and frame size limits.
  • ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift: Caches the active client instance across calls to avoid redundant Keychain reads when the installation and generation have not changed.
  • ios/AidenOnTheGo/Config/AidenAppearance.swift, ios/AidenOnTheGo/Features/Shared/ThinkingOrbsKit/ThinkingOrb.swift, ios/AidenOnTheGo/Features/Bots/AidenBotsHomeView.swift: Observes system Low Power Mode notifications and caps decorative orb and shimmer animations to 30 fps or static frames.
  • ios/AidenOnTheGo.xcodeproj/project.pbxproj: Registers the four new source and test files in their appropriate groups and build phases.
  • ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift: Adds comprehensive behavioral tests for value throttling, markdown splitting/caching, scene refresh gating, and SSE line decoding.

Findings

No findings.

📊 Sequence Diagram
sequenceDiagram
    participant Scene as ScenePhase
    participant ChatView as AidenChatDetailView
    participant ViewModel as AidenChatViewModel
    participant Client as AidenRemoteClient
    participant Throttle as AidenLatestValueThrottle
    participant Activity as ActivityKit

    Note over Scene,ChatView: Background return triggers single-owner reload
    Scene->>ChatView: transition(.active) after .background
    ChatView->>ViewModel: load(observeProgress: true)
    ViewModel->>Client: taskProgress() / agentRoster() (single snapshot)
    ViewModel->>Client: progressEvents() (streamSession: 30s idle / 1h resource)
    Client-->>ViewModel: SSE line decoded (validated UTF-8, CRLF normalized)
    ViewModel->>Throttle: submit(contentState)
    alt Update within 1s window
        Throttle->>Throttle: Coalesce to newest value
    else 1s elapsed or phase change (.immediate)
        Throttle->>Activity: activity.update(content)
    end
Loading

Machine-Readable Findings

[]

Last reviewed commit: a28a1f7c3a79
Reviews (1) · Comment /hermes review to trigger a new review · /hermes review full for full re-review

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues found in this delta. Approval remains withheld because the existing runtime findings are still open.

Reviewed changes: Reviewed the changes since the prior Pullfrog review at a28a1f7c, separating the main merge from the allowlist fix.

  • Registered streaming sources: Added the Markdown cache, scene refresh gate, and latest-value throttle to the reviewed shipping-source inventory.
  • Registered streaming tests: Added AidenStreamingPerformanceTests.swift to the reviewed test-source inventory, preserving the exact source-phase and orphan-source assertions.

Validation: node --test scripts/check-ios-shipping-target.test.mjs passed all 14 tests. Native iOS XCTest was not run on this Linux runner; hosted CI was still pending when inspected.

Pullfrog  | Fix it ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

@sambitcreate
sambitcreate merged commit ad88acd into main Oct 4, 2026
23 checks passed
@sambitcreate
sambitcreate deleted the perf/ios-streaming branch October 4, 2026 10:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants